package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"shuqi-novel/models/mysql"

	"shuqi-novel/shuqirpc/internal/svc"
	"shuqi-novel/shuqirpc/shuqirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookUpdateLogic {
	return &BookUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BookUpdateLogic) BookUpdate(in *shuqirpc.BookUpdateRequest) (*shuqirpc.BookUpdateResponse, error) {
	// todo: add your logic here and delete this line
	//图书修改应该只能修改自己的，如果我要修改不是自己的图书id那么就提示该图书不存在
	var b mysql.Book
	mysql.DB.Debug().Where("id = ?", in.BookId).Where("User_Id = ?", in.UserId).Find(&b)
	if b.ID == 0 {
		return nil, errors.New("该图书不存在")
	}

	book := mysql.Book{
		Model:  gorm.Model{ID: uint(in.BookId)},
		Title:  in.Title,
		UserId: in.UserId,
		Image:  in.Image,
		Info:   in.Info,
	}

	mysql.DB.Debug().Updates(&book)
	return &shuqirpc.BookUpdateResponse{
		BookId: int64(book.ID),
	}, nil
}
